import Vue from 'vue'
import { login, logout,getUserInfo,getMenu} from "@/services/system/api"
import { ACCESS_TOKEN,USER_INFO,USER_TYPE,USER_ADD_ROUTERS} from "@/store/mutation-types"
import {post} from '@/services/http'
import {generator} from '@/utils/routerUtil'
import { constantRouterMap } from '@/router/router.config'
import {rootRouterId} from '@/config/default/setting.config'
const user = {
  state: {
    accessToken: '',
    userInfo: null,
    welcome: '',
    userName: '',
    fullName: '',
    userType:'',
    avatar: '',
    routers:constantRouterMap,
    roles:[],
    addRouters: [],
    orgIds:[],
    openId:'',
    clientId:'',
    currentRouter: {}
  },
  getters: {
    
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.accessToken = token
    },
    SET_NAME: (state, { username, realname, welcome }) => {
      state.userName = username
      state.fullName = realname
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROUTERS: (state, routers) => {
      state.routers = routers
    },
    SET_USER_INFO: (state, userInfo) => {
      state.userInfo = userInfo
      if (userInfo) {
        state.roles= userInfo.roles
        state.userType= userInfo.userType
        state.openId= userInfo.openId
        state.userName=  userInfo.userName
        state.fullName=  userInfo.fullName
        state.orgIds=  userInfo.orgIds
        if(userInfo.photoPath){
          state.avatar = userInfo.photoPath
        }
        state.orgId=  userInfo.orgId
        state.clientId=  userInfo.clientId
      }else{
        state.roles= []
        state.userType= ''
        state.openId= ''
        state.userName=  ''
        state.fullName=  ''
        state.orgIds=  []
        state.avatar = ''
        state.orgId=  ''
        state.clientId= ''
      }
      
    },
    SET_ROLE: (state, roles) => {
      state.roles = roles
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_OPENID: (state, openId) => {
      state.openId = openId
    },
    SET_ORGIDS: (state, orgIds) => {
      state.orgIds = orgIds
    },
    SET_ORGID: (state, orgId) => {
      state.orgId = orgId
    },
    SET_CLIENT_ID: (state, clientId) => {
      state.clientId = clientId
    },
    SET_ADD_ROUTERS(state, addRouters) {
      state.addRouters = addRouters
      if(addRouters&&addRouters.length>0){
        state.routers = constantRouterMap.concat(generator(addRouters))
      }else {
        state.routers =constantRouterMap
      }
    },
    SET_CURRENT_ROUTER: (state, router) => {
      state.currentRouter = router
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        post(login,userInfo).then(response => {
          const code = response.code
          if (code) {
            const error = {}
            error.response = response
            if (code && code !== 0 && code !== 200) {
              reject(error)
            }
          } else {
            const result = response.result
            Vue.ls.set(ACCESS_TOKEN, result.accessToken, result.expireMinute*1000)
            commit('SET_TOKEN', result.accessToken)
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        let params = {};
        post(getUserInfo,params).then(response => {
          const result = response.result
          commit('SET_USER_INFO', result)
          //commit('SET_ROLE', result.roles)
          //commit('SET_USER_TYPE', result.userType)
          //commit('SET_OPENID', result.openId)
          //commit('SET_OPENID', result.openId)
          //commit('SET_ORGIDS', result.orgIds)
          //commit('SET_ORGID', result.orgId)
          //commit('SET_CLIENT_ID', result.clientId)
          Vue.ls.set(USER_INFO, result, result.expireMinute*1000)
          Vue.ls.set(USER_TYPE, result.userType, result.expireMinute*1000)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        //console.log('logoutToken: '+ logoutToken)
        let params = {};
        params.accessToken = state.accessToken
        post(logout,params).then((response) => {
          resolve(response)
        }).catch(() => {
          resolve()
        }).finally(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROUTERS', [])
          commit('SET_USER_INFO', null)
          commit('SET_ADD_ROUTERS', [])
          commit('SET_USER_TYPE', '')
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(USER_INFO)
          Vue.ls.remove(USER_TYPE)
          Vue.ls.remove(USER_ADD_ROUTERS)
          localStorage.setItem(process.env.VUE_APP_ROUTES_KEY, null)
        })
      })
    },
    //获取菜单
    GetRouterMenu({commit}) {
      return new Promise((resolve,reject) => {
        //console.log('logoutToken: '+ logoutToken)
        let params = {}
        params.routerId=rootRouterId
        post(getMenu,params).then((response) => {
          const result = response.result
          if(result&&result.length>0){
            Vue.ls.set(USER_ADD_ROUTERS, result, 7*24*3600*1000)
            commit('SET_ADD_ROUTERS', result)
            resolve(result)
          }else{
            resolve(result)
          }
          
        }).catch(error => {
          reject(error)
        })
      })
    },
    setCurrentRouter ({ commit }, data) {
      return new Promise(resolve => {
        commit('SET_CURRENT_ROUTER', data)
        resolve()
      })
    }
  }
}

export default user